package vg.modules.opener;

import vg.modules.opener.decoders.IDecoder;
import vg.modules.opener.decoders.VGDBDecoder;
import vg.modules.opener.decoders.dot.DotDecoder;
import vg.modules.opener.decoders.graphml.GraphMLDecoder;
import vg.interfaces.ll_services.data_base_service.IGraphDataBaseService;
import vg.services.main_manager.VGMainServiceHelper;

import java.io.File;
import java.util.*;

/**
 * Console opener.
 *
 * @author Timur Zolotuhin (e-mail: tzolotuhin@gmail.com)
 */
public class ConsoleOpener {
    // Main data
    private static boolean init = false;

    private static HashMap<String,IDecoder> decoders;
    private static ArrayList<String> openedFilesList;

    // Mutex
    private static final Object generalMutex = new Object();

    public static void init() {
        synchronized (generalMutex) {
            if (init)
                return;

            decoders = new HashMap<String, IDecoder>();
            openedFilesList = new ArrayList<String>();

            decoders.put("graphml", new GraphMLDecoder());
            decoders.put("vgdb", new VGDBDecoder());
            decoders.put("dot", new DotDecoder());
            decoders.put("gv", new DotDecoder());

            init = true;
        }
    }

    /**
     * This method reads a graph (or graphs) from the file and
     * returns list of graph model indexes.
     */
    public static List<Integer> openFile(File file, IGraphDataBaseService graphDataBase) throws Exception {
        init();

        //getting decoder for file
        String extension = file.getName().toLowerCase().replaceAll(".*\\.", "");

        IDecoder decoder = decoders.get(extension);
        if (decoder == null)
            throw new Exception("Couldn't find decoder for *." + extension + "file");

        Date d = new Date();

        List<Integer> graphModelIds = decoder.decode(file, graphDataBase, file.getName().replaceFirst("\\..*$", ""));
        if (graphModelIds == null || graphModelIds.isEmpty()) {
            VGMainServiceHelper.logger.printError("[BAD] Cannot to add graph in graphDataBase.");
            throw new Exception("Cannot to add graph in graphDataBase.");
        }
        openedFilesList.add(file.getName());
        VGMainServiceHelper.logger.printInfo("Graph load time: " + (new Date().getTime() - d.getTime()) / 1000.0 + "sec");
        return graphModelIds;
    }

    public static Set<String> getAvailableExtensions() {
        init();

        return decoders.keySet();
    }

    public static List<String> getOpenedFilesList() {
        init();

        return openedFilesList;
    }
}
